//
//  ViewController.m
//  Polyline
//
//  Created by saber on 2022/4/5.
//

#import "ViewController.h"
#import "XMLReader.h"
#import <CoreLocation/CoreLocation.h>

#define  DefaultLatitude 31.22629
#define  DefaultLongitude 121.63948

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *reslutLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor cyanColor];
    
    NSDictionary* result = [self findminimumDistanceFromGPXLine];
    if (result) {
        self.reslutLabel.text = [NSString stringWithFormat:@"Min distance :%.2f \n Is coordinates: %@,  %@",[result[@"minDistance"] doubleValue],result[@"point"][@"lat"],result[@"point"][@"lon"]];
    }
}


-(NSDictionary*)findminimumDistanceFromGPXLine{
    //Get pgx file content
    NSString *xmlFileString = [[NSBundle mainBundle] pathForResource:@"polyline" ofType:@"gpx"];
       NSData *xmlData = [NSData dataWithContentsOfFile:xmlFileString];
       NSError *error = nil;
       if (error) {
           return nil;
       }
       
    NSDictionary *result = [XMLReader dictionaryForXMLData:xmlData error:&error];
    NSArray*trkpt = result[@"gpx"][@"trk"][@"trkseg"][@"trkpt"];
    
    //min distance
    double minDistance = -1;
    NSDictionary* minDistancePoint = nil;
    
    CLLocation* otherLocation = [[CLLocation alloc] initWithLatitude:DefaultLatitude longitude:DefaultLongitude];
    
    for (int i = 0; i < trkpt.count; i++){
        
        NSDictionary* dict =trkpt[i];
        double lat = [dict[@"lat"] doubleValue];
        double lon = [dict[@"lon"] doubleValue];
        
        CLLocation* curLocation = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
        
        //Retrieves the distance between two coordinates;
        double curDistance = [curLocation distanceFromLocation:otherLocation];
        
        if (minDistance < 0) {
            // init last distances
            minDistance = curDistance;
        }else{
            //If the current distance is less than the last min distance, the current distance is min
            if (curDistance < minDistance) {
                minDistance = curDistance;
                minDistancePoint = @{@"lat":@(lat),@"lon":@(lon)};
            }
        }
    }
    return @{@"minDistance":@(minDistance),@"point":minDistancePoint};
}

@end
